import { ref } from 'vue';
import { events } from '../../utils/events.js';
import { contentRef } from '../contentContainer/content.js';

const dragComponent = ref(null);
let index;

export const setDragHandle = (dataList) => {
    const dragstart = (event, component) => {
        dragComponent.value = component;
        contentRef.value.addEventListener('dragenter', dragenter)
        contentRef.value.addEventListener('dragover', dragover)
        contentRef.value.addEventListener('dragleave', dragleave)
        contentRef.value.addEventListener('drop', drop)
        events.emit('start');
    }
    const dragend = () => {
        contentRef.value.removeEventListener('dragenter', dragenter)
        contentRef.value.removeEventListener('dragover', dragover)
        contentRef.value.removeEventListener('dragleave', dragleave)
        contentRef.value.removeEventListener('drop', drop)
        events.emit('end');
    }

    // dragenter 进入元素中，添加一个移动的标识
    const dragenter = (e) => {
        e.dataTransfer.dropEffect = "move";
    }
    // dragover 在目标元素中经过时，必须阻止默认行为
    const dragover = (e) => {
        e.preventDefault()
        for(let i = 0; i < dataList.value.length; i++) {
            if(dataList.value[i].drag) {
                dataList.value.splice(i+1, 1)
            }
            if(e.clientY > dataList.value[i].dom.y) {
                index = i;
                
                dataList.value.splice((i + 1), 0, {
                    key: dragComponent.value.key,
                    id: Math.random().toString(),
                    props: dragComponent.value.props,
                    focus: false,
                    drag: true,
                })
            }
        }
    }
    // dragleave 离开元素的时候，需要增加一个禁用标识
    const dragleave = (e) => {
        e.dataTransfer.dropEffect = "none";
    }
    // drop 松手时，根据拖拽的组件，给编辑区添加一个组件
    const drop = () => {
        dataList.value.splice((index == undefined ? 0 : index + 1), 0, {
            key: dragComponent.value.key,
            id: Math.random().toString(),
            props: dragComponent.value.props,
            focus: false,
        })
    }

    return {
        dragstart,
        dragend
    }
}